<?php
/**
 * CreateTime: 2023/1/10 15:23
 */

namespace App\Http\Controllers\MeLawCase;

use App\common\iPermission;
use App\common\tiPermissionCheck;
use App\Consts\BaseConsts\BaseConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseListConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Enum\MeLawCaseEnum\MeLawCaseStatusEnum;
use App\Func\MeLawCaseAllocation;
use App\Func\MeLawCaseFunc;
use App\Func\ResponseFunc;
use App\Func\ScopeFunc\AuthScopeStaffFunc;
use App\Func\StaffFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListBasicRequest;
use App\Http\Requests\MeLawCase\AcceptancePostRequest;
use App\Http\Requests\MeLawCase\lawCaseAllocationInfoRequest;
use App\Http\Requests\MeLawCase\LawCaseAllocationRequest;
use App\Http\Requests\MeLawCase\MeLawCaseAddPhoneRequest;
use App\Http\Requests\MeLawCase\MeLawCaseAddRequest;
use App\Http\Requests\MeLawCase\MeLawCaseBindMeDetail;
use App\Http\Requests\MeLawCase\MeLawCaseBindMeDetailRemark;
use App\Http\Requests\MeLawCase\MeLawCaseFollow;
use App\Http\Requests\MeLawCase\MeLawCaseBindMediator;
use App\Http\Requests\MeLawCase\MeLawCaseMediatorGoExtensions;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseBindMeDetails;
use App\Models\MeLawCase\MeLawCaseFollowModel;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use App\Models\MeMediator\MediationAgreementModel;
use App\Models\modelSystemOperationLog;
use App\Models\modelSystemOperationLogConstCategory;
use App\Models\SMS\SMSLogModel;
use App\Models\Staff\StaffModel;
use App\Scopes\MediationStaffScope;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class MeLawCaseController extends Controller implements iPermission
{
    use tiPermissionCheck;
    private MeLawCase $meLawCaseModel;
    private modelSystemOperationLog $lawCaseOperate;

//    private function bigAuth(){
//        $this->canRead (
//            [
//                // 查看合同详情
//                'getContractInfo'	=>	[
//                    [
//                        'auth_code' => cPermissionAuthCode::NEW_AUTH_CONTRACT_INFO,
//                        'data_permission' => iPermission::PERMISSION_READ
//                    ],
//                ]
//            ]
//        )->setOnErrorVerifiedPermission( function($o_error){
//        });
//    }


    public function __construct()
    {
        $this->meLawCaseModel = new MeLawCase();
        $staff_id = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $this->lawCaseOperate = new modelSystemOperationLog ($staff_id, modelSystemOperationLogConstCategory::LOG_TYPE_LAW_CASE);		# system operation log

    }


    public function getLawCaseStatusSelect(){
        $res = MeLawCaseStatusEnum::getEnumMapList();
        return ResponseFunc::returnJson(
            'ok',
            $res,
            '获取案件状态成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 设置新增默认值
     * @param $data
     * @return mixed
     */
    private function setAddDefault($data){
        $count = rand(1,9);
        $data['law_case_code'] = MeLawCaseFunc::getLawCaseUnionCode($data['client_id'],$count);
        $data['law_case_status'] = MeLawCaseConsts::ME_LAW_CASE_DFP_1;
        // 时间处理
//        $data['loans_time'] = date("Y-m-d",$data['loans_time']);
//        $data['loans_start_time'] = date("Y-m-d",$data['loans_start_time']);
//        $data['loans_overdue_time'] = date("Y-m-d",$data['loans_overdue_time']);
        $data['owner_id'] = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $data['status'] = BaseConsts::STATUS_NORMAL;
        return $data;
    }

    /**
     * 调解员绑定
     * @param MeLawCaseBindMediator $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindMediator(MeLawCaseBindMediator $request){
        try {
            $data = $request->all();
            $ids = explode(',',$data['law_case_list']);
            // 校验当前 mediator_id 是否为当前登录账号 和状态是否为已分配
            $errorDatas = $this->meLawCaseModel->select(['law_case_id'])
                ->withoutGlobalScopes()
                ->where('status', 1)
                ->where('law_case_status', MeLawCaseConsts::ME_LAW_CASE_DFP_1)
                ->whereIn('law_case_id',$ids)
                ->get();

            // 对比两个数组的差异
            $diffCount = 0;
            if($errorDatas){
                $diff = array_diff($ids, array_column($errorDatas->toArray(),'law_case_id'));
                $diffCount = count($diff);
            }

            $this->meLawCaseModel->bindMediator($data['mediator_id'],$ids);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'total' => count($ids),
                    'okNumber' => count($ids) - $diffCount,
                    'jumpNumber' => $diffCount
                ],
                '绑定调解员成功',
                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '绑定调解员失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 批量进入外呼系统
     */
    public function mediatorGoExtensions(MeLawCaseMediatorGoExtensions $request){
        // 校验案件调解员是本人
        $data =$request->all();
        $staffInfo = TokenFuc::getCurrentStaffInfo();
        $lawCases = $this->meLawCaseModel->getLawCaseByIds(explode(',',$data['law_case_list']),[
            'law_case_code','law_case_id','mediator_id','law_case_status'
        ]);
        $err = "";
        $errStatus = "";
        foreach($lawCases as $key => $value){
            if($value['law_case_status']!=MeLawCaseConsts::ME_LAW_CASE_YSL_9){
                $errStatus =  $value['law_case_code'];
                break;
            }
            if($staffInfo['staff_id']!=$value['mediator_id']){
                $err =  $value['law_case_code'];
                break;
            }
        }
        if($errStatus){
            return ResponseFunc::returnJson(
                'error',
                null,
                "$errStatus"."未受理",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        if($err){
            return ResponseFunc::returnJson(
                'error',
                null,
                "$err"."不属于当前经办人",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $lawCases = explode(',',$data['law_case_list']);
        $this->meLawCaseModel->updateLawCaseByIds($lawCases,[
            'law_case_status' => MeLawCaseConsts::ME_LAW_CASE_WHTJZ_3
        ]);
        foreach($lawCases as $value){
            $this->lawCaseOperate->addSystemOperationLog("移交给外呼",$value,[]);
        }
        return ResponseFunc::returnJson(
            'ok',
            null,
            '外呼移交成功',
            ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
        );
    }

    /**
     * 外呼转调解员调解
     */
    public function extensionsGoMediator(int $lawCaseId){
        // 校验当前案件是否为外呼调解中 只允许外呼调解中的案件转外呼处理、
        $lawCaseInfo = $this->meLawCaseModel->getById($lawCaseId,['law_case_status']);
        if($lawCaseInfo['law_case_status']!=MeLawCaseConsts::ME_LAW_CASE_WHTJZ_3){
            return ResponseFunc::returnJson(
                'error',
                null,
                '状态异常',
                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
            );
        }
        $this->meLawCaseModel->updateData([
           'law_case_id' => $lawCaseId,
           'law_case_status' => MeLawCaseConsts::ME_LAW_CASE_RYTJZ_4
        ]);
        $this->lawCaseOperate->addSystemOperationLog("移交给调解员",$lawCaseId,[]);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '调解员移交成功',
            ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
        );
    }
//    取消校验
//    public function addLawCase(MeLawCaseAddRequest $request){
    # 创建案件（待分配） -> 分配案件（已分配）->调解员受理（）
    public function addLawCase(){
        try {
            $data = request()->all();
            // 校验当前委托方是否存在
            $clientIsExists = (new MeClientModel())->isExistByCondition([
                'client_id' => $data['client_id'],
                'status' => BaseConsts::STATUS_NORMAL
            ]);
            if(!$clientIsExists){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '当前委托方不存在',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
            $data = $this->setAddDefault($data);
            return ResponseFunc::returnJson(
                'ok',
                ['law_case_id' => $this->meLawCaseModel->add($data)],
                '新建案件成功',
                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '新建案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function editLawCase($lawCaseId){
        try {
            $data = request()->all();
            $data['law_case_id'] = $lawCaseId;
            unset($data['client_id']);
            unset($data['status']);
            unset($data['law_case_code']);
            unset($data['law_case_status']);
            unset($data['owner_id']);
            // 处理时间
//            if(isset($data['loans_time'])){
//                $data['loans_time'] = date("Y-m-d",$data['loans_time']);
//            }
//            if(isset($data['loans_start_time'])){
//                $data['loans_start_time'] = date("Y-m-d",$data['loans_start_time']);
//            }
//            if(isset($data['loans_overdue_time'])){
//                $data['loans_overdue_time'] = date("Y-m-d",$data['loans_overdue_time']);
//            }
            $this->meLawCaseModel->updateData($data);
            $this->lawCaseOperate->addSystemOperationLog("编辑案件",$lawCaseId,json_encode($data));
            return ResponseFunc::returnJson(
                'ok',
                null,
                '编辑案件成功',
                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '编辑案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function delLawCase($lawCaseId){
        try {
            $data = [
                'law_case_id' => $lawCaseId,
                'status' => BaseConsts::STATUS_DELETE
            ];
            $this->meLawCaseModel->updateData($data);
            $this->lawCaseOperate->addSystemOperationLog("删除了案件",$lawCaseId,json_encode($data));
            return ResponseFunc::returnJson(
                'ok',
                null,
                '删除案件成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '删除案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 用于话单和案件的初次绑定
     * @param MeLawCaseBindMeDetail $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lawCaseBindMeDetail(MeLawCaseBindMeDetail $request){
        $data = $request->all();
        try {
            $res = (new MeLawCaseBindMeDetails())->add($data);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'law_case_bind_details_id' =>$res
                ],
                '绑定话单案件成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'ok',
                null,
                '绑定话单案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 外呼备注
     * @param MeLawCaseBindMeDetail $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lawCaseBindMeDetailRemark(int $law_case_bind_details_id,MeLawCaseBindMeDetailRemark $request){
        $data = $request->all();
        $data['law_case_bind_details_id'] = $law_case_bind_details_id;
        $data['owner_id'] = TokenFuc::getCurrentStaffInfo()['staff_id'];
        try {
            $res = (new MeLawCaseBindMeDetails())->updateData($data);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '外呼备注添加成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'ok',
                null,
                '外呼备注添加失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }



    /**
     * 设置案件外呼跟进状态
     */
    public function lawCaseWhFollow(int $law_case_id, MeLawCaseFollow $request){
        $data = $request->all();
        $data['law_case_id'] = $law_case_id;
        $data['owner_id'] = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $this->lawCaseOperate->addSystemOperationLog("外呼跟进案件",$law_case_id,json_encode($data));
        try {
            $res = (new MeLawCaseFollowModel())->add($data);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'law_case_follow_id' =>$res
                ],
                '外呼跟进案件成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '外呼跟进案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getSelfLawCaseList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $select = $request->get('select') ?? false;
            $pageSize = $request->get('page_size');
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $staffInfo = TokenFuc::getCurrentStaffInfo();
            $query = $this->setListDefaultSQL()->where('law_case.mediator_id',$staffInfo['staff_id']);
            if($filters){
                $query = $this->setListDefaultFilters($query,$filters);
            }

            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];
            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取我的案件列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取我的案件列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 获取调解员正式受理列表
     */
    public function getMeMediatorAcceptList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $select = $request->get('select') ?? false;
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $staffInfo = TokenFuc::getCurrentStaffInfo();
            $query = $this->meLawCaseModel->select([
                'law_case.law_case_id',
                'law_case.law_case_id as key',
                'law_case.client_id',
                'law_case.mediator_id',
                'law_case.law_case_code',
                'law_case.law_case_status',
                'law_case.respondent_name',
                'law_case.respondent_id_card',
                'law_case.loans_name',
                'law_case.loans_contract_code',
                'law_case.start_mediator_time',
                'case_phone.phone_number',
            ])->leftJoin(TableConsts::ME_LAW_CASE_PHONE." as case_phone",'case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
            ->where('law_case.mediator_id',$staffInfo['staff_id'])
            ->where('law_case.status',BaseConsts::STATUS_NORMAL);
            if($filters){
                if(isset($filters['client_id']) && $filters['client_id']){
                    $query = $query->where('law_case.client_id',$filters['client_id']);
                }
                if(isset($filters['law_case_status']) && $filters['law_case_status']){
                    $query = $query->where('law_case.law_case_status',$filters['law_case_status']);
                }
                if(isset($filters['law_case_code']) && $filters['law_case_code']){
                    $query = $query->where('law_case.law_case_code','LIKE',"%".$filters['law_case_code']."%");
                }
                if(isset($filters['respondent_name']) && $filters['respondent_name']){
                    $query = $query->where('law_case.respondent_name','LIKE',"%".$filters['respondent_name']."%");
                }
                if(isset($filters['respondent_id_card']) && $filters['respondent_id_card']){
                    $query = $query->where('law_case.respondent_id_card','LIKE',"%".$filters['respondent_id_card']."%");
                }
                if(isset($filters['respondent_phone']) && $filters['respondent_phone']){
                    $query = $query->where('case_phone.phone_number','LIKE',"%".$filters['respondent_phone']."%");
                }
                if(isset($filters['loans_name']) && $filters['loans_name']){
                    $query = $query->where('law_case.loans_name','LIKE',"%".$filters['loans_name']."%");
                }
                if(isset($filters['loans_contract_code']) && $filters['loans_contract_code']){
                    $query = $query->where('law_case.loans_contract_code','LIKE',"%".$filters['loans_contract_code']."%");
                }
            }
            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];
            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取我的正式调解列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){

            return ResponseFunc::returnJson(
                'error',
                null,
                '获取我的正式调解列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getWhSelfLawCaseList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $select = $request->get('select') ?? false;
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $query = $this->setListDefaultSQL()->where('law_case.law_case_status',MeLawCaseConsts::ME_LAW_CASE_WHTJZ_3);

            # 增加筛选项
            #
            #
            if($filters)
            {
                # modified by		: BEEZEER @2023/6/6
                # tips				:
                #					1. 通过 mediator_id 过滤
                #
                #
                #
                $mediator_id	= @$filters['mediator_id'];
                if($mediator_id==''){

                }else
                {
                    $query->where('law_case.mediator_id',$mediator_id);
                }
                $seats_id = @$filters['seats_id'];
                if($seats_id == ''){}else{
                    $query->where('law_case.seats_id',$seats_id);
                }

                #
                #
                #
                $query = $this->setListDefaultFilters($query,$filters);
            }

            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];
            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->disposeDataWh($data['data'][$key]);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取外呼列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取外呼列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getLawCaseInfoV2($lawCaseId){
        $ar = [];
        $res =    app()->gcHelper->gfDbQuery()->select("SELECT
  `cy_law_case`.*,
  `cy_client`.`client_name`,
  IFNULL(`cy_law_case_wh_follow`.`law_case_wh_follow_status`, NULL) AS `law_case_wh_follow_status`,
  IFNULL(`cy_law_case_wh_follow`.`created_time`, NULL) AS `recently_follow`,
  IFNULL(`cy_law_case_law_letter`.`pdf_path_hash`, NULL) AS `pdf_path_hash`
FROM
  `cy_law_case`
  LEFT JOIN (
    SELECT *
    FROM `cy_law_case_wh_follow`
    WHERE `cy_law_case_wh_follow`.`law_case_id` = ?
    ORDER BY `cy_law_case_wh_follow`.`law_case_wh_follow_id` DESC
    LIMIT 1
  ) AS `cy_law_case_wh_follow` ON `cy_law_case_wh_follow`.`law_case_id` = `cy_law_case`.`law_case_id`
  LEFT JOIN `cy_client` ON `cy_client`.`client_id` = `cy_law_case`.`client_id`
  LEFT JOIN `cy_law_case_law_letter` ON `cy_law_case_law_letter`.`law_case_id` = `cy_law_case`.`law_case_id`
WHERE
  `cy_law_case`.`law_case_id` = ?;
",[$lawCaseId,$lawCaseId],debug:false)->forEachRow(	function($row)
        {
            return $row->getOneRowAllDataNotFmt();
        },
            $ar);
        try {
            $res = $ar['content'][0];

            $staffAll = StaffFunc::getStaffAllBySelect();
            $res = $this->disposeDataV2($res,$staffAll);

            $res = $this->disposeDataWhV2($res,true);
            // 查询关联表信息
            $bindInfo = (new MeLawCaseBindMeDetails())->getByLawCaseId($lawCaseId);
            $res['me_details_uuid_list'] = $bindInfo ?? [];
            $res['law_case_wh_follow_list'] = (new MeLawCaseFollowModel())->getByLawCaseId($lawCaseId,[
                'law_case_id',
                'law_case_wh_follow_remark',
                'law_case_wh_follow_status',
                'created_time',
                'owner_id',
                'owner_id as owner_str'
            ]);
            // 获取调解函code
            $mediationAgreementInfo = (new MediationAgreementModel())->getByLawCaseId($lawCaseId,[
                'mediation_agreement_code',
                'file_id'
            ]);
            $res['mediation_agreement_code'] = $mediationAgreementInfo['mediation_agreement_code'] ?? "";
            $res['mediation_agreement_file_id'] = $mediationAgreementInfo['file_id'] ?? 0;

            $res['operate_list'] = $this->lawCaseOperate->getSystemOperationLog($lawCaseId);
            $res = $this->setMeClientAuth($res);



            return ResponseFunc::returnJson(
                'ok',
                $res,
                '获取案件详情成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){

            return ResponseFunc::returnJson(
                'error',
                null,
                '获取案件详情失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }


    public function getLawCaseInfo($lawCaseId){
        try {
            $res = $this->meLawCaseModel->getById($lawCaseId);
            $staffAll = StaffFunc::getStaffAllBySelect();
            $res = $this->disposeData($res,$staffAll);
            $res = $this->disposeDataWh($res,true);
            // 查询关联表信息
            $bindInfo = (new MeLawCaseBindMeDetails())->getByLawCaseId($lawCaseId);
            $res['me_details_uuid_list'] = $bindInfo ?? [];
            $res['law_case_wh_follow_list'] = (new MeLawCaseFollowModel())->getByLawCaseId($lawCaseId,[
                'law_case_id',
                'law_case_wh_follow_remark',
                'law_case_wh_follow_status',
                'created_time',
                'owner_id',
                'owner_id as owner_str'
            ])->withoutGlobalScope(MediationStaffScope::class)
            ->whereIn('law_case.owner_id',AuthScopeStaffFunc::getDepartmentStaffByCurrentStaffId());
            // 获取调解函code
            $mediationAgreementInfo = (new MediationAgreementModel())->getByLawCaseId($lawCaseId,[
                'mediation_agreement_code',
                'file_id'
            ]);
            $res['mediation_agreement_code'] = $mediationAgreementInfo['mediation_agreement_code'] ?? "";
            $res['mediation_agreement_file_id'] = $mediationAgreementInfo['file_id'] ?? 0;

            $res['operate_list'] = $this->lawCaseOperate->getSystemOperationLog($lawCaseId);
            $res = $this->setMeClientAuth($res);

            return ResponseFunc::returnJson(
                'ok',
                $res,
                '获取案件详情成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取案件详情失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 调解函列表
     * @param ListBasicRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLawCaseList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            // 快速筛选功能
            $select = $request->get('select') ?? false;
            $pageSize = $request->get('page_size');
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $query = $this->setListDefaultSQLDepartment()
                ->where('law_case.status',BaseConsts::STATUS_NORMAL);
            if($filters){
                $query = $this->setListDefaultFilters($query,$filters);
            }

            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];

            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeListData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取案件列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取案件列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getLawCaseLawLatterList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $select = $request->get('select') ?? false;
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            $query = $this->meLawCaseModel->select([
                'law_case.law_case_id',
                'law_case.law_case_id as key',
                'law_case.client_id',
                'law_case.respondent_phone_ids',
                'law_case.mediator_id',
                'law_case.law_case_code',
                'law_case.law_case_status',
                'law_case.respondent_name',
                'law_case.respondent_id_card',
                'law_case.loans_name',
                'law_case.seats_id',
                'law_case.loans_contract_code',
                'law_case.loans_output_money',
                'law_case.law_case_custom',
                'law_case.is_send_law_latter',
                'client.client_name',
                'latter.read_time',
                'latter.pdf_path_hash as hash_code',
                'latter.recently_read_time',
                'latter.progress',
                'latter.browser',
                'latter.duration',
                'latter.read_count',
                'case_phone.phone_number',
                'law_case.law_case_batch_number',
            ])
            ->leftJoin(TableConsts::ME_CLIENT.' as client','client.client_id','law_case.client_id')
            ->leftJoin(TableConsts::ME_LAW_CASE_PHONE.' as case_phone','case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
            ->leftJoin(TableConsts::LAW_CASE_LAW_LETTER.' as latter','latter.law_case_id','law_case.law_case_id')
            # 禁止全局 手动处理
            ->withoutGlobalScope(MediationStaffScope::class)
            ->whereIn('law_case.owner_id',AuthScopeStaffFunc::getDepartmentStaffByCurrentStaffId());;

            if($filters){
                $query = $this->setListDefaultFilters($query,$filters);
                if(isset($filters['letter_send_status'])){
                    switch ($filters['letter_send_status']){
                        case 'wait':
                            $query = $query->where('law_case.is_send_law_latter',2);
                            break;
                        case 'send':
                            $query = $query->where('law_case.is_send_law_latter',1);
                            $query = $query->where('latter.read_count',0);
                            break;
                        case 'read':
                            $query = $query->where('latter.read_count','>=',1);
                            break;
                    }
                }
            }

            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case.law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case.law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];
            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeListData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取案件列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取案件列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getSelfWhLawCaseList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $select = $request->get('select') ?? false;
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            // 匹配当前登录的坐席id
            // 开启查询日志记录
            $query = $this->setListDefaultSQL()
                ->leftjoin(TableConsts::ME_LAW_CASE_FOLLOW.' as follow','follow.law_case_id','law_case.law_case_id')
                ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                ->where('law_case.seats_id',TokenFuc::getCurrentStaffInfo()['staff_id']);
            if($filters)
            {
                $mediator_id	= @$filters['mediator_id'];
                if($mediator_id==''){}else
                {
                   $query->where('law_case.mediator_id',$mediator_id);
                }

                $extensions_status	= @$filters['extensions_status'];
                if($extensions_status==''){}else
                {
                    $query->where('follow.law_case_wh_follow_status',$extensions_status);
                }
                $query = $this->setListDefaultFilters($query,$filters);
            }

            // 存在筛选条件和select以后
            if($select && $filters){
                $queryx = clone $query;
                $ids = $queryx->select(['law_case.law_case_id'])
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->orderBy('law_case_id','desc')
                    ->get()
                    ->toArray();
                $fmt_ids = array_column($ids,'law_case_id');
            }

            $data = $query
                    // 仅显示外呼调解中
                    ->where('law_case.law_case_status',MeLawCaseConsts::ME_LAW_CASE_WHTJZ_3)
                    ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                    ->groupBy('law_case.law_case_id')
                    ->orderBy('law_case.law_case_id','desc')
                    ->Paginate($pageSize)->toArray() ?? [];
            // 获取已执行的 SQL 查询语句
            $staffAll = StaffFunc::getStaffAllBySelect();
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeListData($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->disposeDataWh($data['data'][$key],$staffAll);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }

            $data['select_ids'] = $fmt_ids ?? [];
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取我的外呼案件列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取我的外呼案件失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 新增受理人手机号
     * @param MeLawCaseAddPhoneRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addLawCaseRespondentPhone(MeLawCaseAddPhoneRequest $request){
        $data = $request->all();
        $phone = $data['phone_number'];
        $isWd = $data['is_wd'] ?? 2;
        // 校验当前手机号是否存在如果存在直接返回当前手机号的id不再新增
        $info = (new MeLawCasePhoneModel())
            # 禁止全局 手动处理
        ->where('phone_number',$phone)->first();
        try {
            if($info){
                return ResponseFunc::returnJson(
                    'ok',
                    [
                        'law_case_phone_id' => $info['law_case_phone_id']
                    ],
                    '新增被申请人手机号成功',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }else{
                $res = (new MeLawCasePhoneModel())->add([
                    'phone_number' => $phone,
                    'is_wd' => $isWd
                ]);
                return ResponseFunc::returnJson(
                    'ok',
                    [
                        'law_case_phone_id' => $res
                    ],
                    '新增被申请人手机号成功',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '新增被申请人手机号失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 编辑受理人手机号
     * @param int $law_case_phone_id
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function editLawCaseRespondentPhone(int $law_case_phone_id){
        $data = request()->all();
        $data['law_case_phone_id'] = $law_case_phone_id;
        try {
            $res = (new MeLawCasePhoneModel())->updateData($data);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '编辑被申请人手机号成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                  null,
                '编辑被申请人手机号失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getLawCaseRespondentPhone(int $law_case_phone_id){
        try {
            $res = (new MeLawCasePhoneModel())->getById($law_case_phone_id,[
                'law_case_phone_id',
                'law_case_phone_id as key',
                'phone_number',
                'phone_status',
                'phone_status as phone_status_str',
                'is_law_case_main_phone',
                'created_time',
                'updated_time'
            ]);
            return ResponseFunc::returnJson(
                'ok',
                $res,
                '获取手机号详情成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取手机号详情失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    private function setListDefaultSQL(){
        return $this->meLawCaseModel->select([
            'law_case.law_case_id',
            'law_case.law_case_id as key',
            'law_case.client_id',
            'law_case.respondent_phone_ids',
            'law_case.mediator_id',
            'law_case.law_case_code',
            'law_case.law_case_status',
            'law_case.respondent_name',
            'law_case.respondent_id_card',
            'law_case.loans_name',
            'law_case.seats_id',
            'law_case.loans_contract_code',
            'law_case.law_case_custom',
            'law_case.loans_output_money',
            'law_case.loans_remaining_principal',
            'law_case.law_case_batch_number',
            'law_case.department_id',
            'law_case.department_id as department_str',
            'case_phone.law_case_phone_id',
            'case_phone.phone_number',
            'client.client_name',
        ])
            ->leftJoin(TableConsts::ME_CLIENT.' as client','client.client_id','law_case.client_id')
            ->leftJoin(TableConsts::ME_LAW_CASE_PHONE." as case_phone",'case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
            # 禁止全局 手动处理
            ->withoutGlobalScope(MediationStaffScope::class)
            ->whereIn('law_case.owner_id',AuthScopeStaffFunc::getDepartmentStaffByCurrentStaffId());

     }

    private function setListDefaultSQLDepartment(){
        return $this->meLawCaseModel->select([
            'law_case.law_case_id',
            'law_case.law_case_id as key',
            'law_case.client_id',
            'law_case.respondent_phone_ids',
            'law_case.mediator_id',
            'law_case.law_case_code',
            'law_case.law_case_status',
            'law_case.respondent_name',
            'law_case.respondent_id_card',
            'law_case.loans_name',
            'law_case.seats_id',
            'law_case.loans_contract_code',
            'law_case.law_case_custom',
            'law_case.loans_output_money',
            'law_case.loans_remaining_principal',
            'law_case.law_case_batch_number',
            'law_case.department_id',
            'law_case.department_id as department_str',
            'case_phone.law_case_phone_id',
            'case_phone.phone_number',
            'client.client_name',
        ])
            ->leftJoin(TableConsts::ME_CLIENT.' as client','client.client_id','law_case.client_id')
            ->leftJoin(TableConsts::ME_LAW_CASE_PHONE." as case_phone",'case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
            # 禁止全局 手动处理
            ->withoutGlobalScope(MediationStaffScope::class)
            ->whereIn('law_case.owner_id',AuthScopeStaffFunc::getDepartmentStaffByCurrentStaffId());

     }

    private function setListDefaultFilters($query,$filters){
        if(isset($filters['law_case_batch_number']) && $filters['law_case_batch_number']){
            $query = $query->where('law_case.law_case_batch_number',$filters['law_case_batch_number']);
        }
        if(isset($filters['client_id']) && $filters['client_id']){
            $query = $query->where('law_case.client_id',$filters['client_id']);
        }
        if(isset($filters['law_case_batch_number']) && $filters['law_case_batch_number']){
            $query = $query->where('law_case.law_case_batch_number',$filters['law_case_batch_number']);
        }
        if(isset($filters['law_case_status']) && $filters['law_case_status']){
            $query = $query->where('law_case.law_case_status',$filters['law_case_status']);
        }
        if(isset($filters['law_case_code']) && $filters['law_case_code']){
            $query = $query->where('law_case.law_case_code','LIKE',"%".$filters['law_case_code']."%");
        }
        if(isset($filters['respondent_name']) && $filters['respondent_name']){
            $query = $query->where('law_case.respondent_name','LIKE',"%".$filters['respondent_name']."%");
        }
        if(isset($filters['respondent_id_card']) && $filters['respondent_id_card']){
            $query = $query->where('law_case.respondent_id_card','LIKE',"%".$filters['respondent_id_card']."%");
        }
        if(isset($filters['respondent_phone']) && $filters['respondent_phone']){
           $query = $query->where('case_phone.phone_number','LIKE',"%".$filters['respondent_phone']."%");
        }
        if(isset($filters['loans_name']) && $filters['loans_name']){
            $query = $query->where('law_case.loans_name','LIKE',"%".$filters['loans_name']."%");
        }
        if(isset($filters['loans_contract_code']) && $filters['loans_contract_code']){
            $query = $query->where('law_case.loans_contract_code','LIKE',"%".$filters['loans_contract_code']."%");
        }
        if(isset($filters['is_allocate_seats']) && $filters['is_allocate_seats']){
            switch ($filters['is_allocate_seats']){
                case 2:
                    $query = $query->where('law_case.seats_id',0);
                    break;
                case 3:
                    $query = $query->where('law_case.seats_id','!=',0);
                    break;
                default:
                    break;
            }
        }
        return $query;
    }

    private function setMeClientAuth($data){
        // 分配
        $canDistribution = false;
        // 详情
        $canInfo = true;
        // 编辑
        $canEdit = false;
        // 删除
        $canDelete = false;
        // 跟进
        $canFollow = false;
        // 电呼
        $canCallPhone = false;
        // 发短信
        $canSendSMS =false;
        // 移交调解
        $canToTj = false;
        // 结案
        $canOverLawCase = false;
        // 转外呼调解
        $canToWh = false;
        // 直接调解
        $canToSelf = false;
        // 修改手机号码
        $canInfoEditPhone = false;
        // 生成受理通知书
        $canCreateNotice = true;
        // 生成调解函
        $canCreateMediation = false;
        // 调解会议纪要
        $canMediateMeeting = false;
        // 回访记录
        $canMeetingFallback = false;
        // 提交协议
        $canCommitAgreement = false;
        // 转诉讼
        $canToSuSong = false;
        // 转执行
        $canToZhiXing = false;
        // 受理
        $canAcceptance = false;
        // 不受理
        $canRefundAcceptance = false;


        // 如果当前案件状态 = law_case_status
        switch ($data['law_case_status']){
            // 待分配 分配 详情 编辑 删除 生成通知书
            case MeLawCaseConsts::ME_LAW_CASE_DFP_1:
                $canDistribution = true;
                $canDelete = true;
                $canEdit = true;
                break;
            // 已分配的案件可以 编辑 受理 不受理 详情
            case MeLawCaseConsts::ME_LAW_CASE_YFP_2:
                $canAcceptance = true;
                $canRefundAcceptance = true;
                $canToWh = false;
                $canToTj = false;
                // TODO 暂时取消
                $canToSuSong = false;
                break;
            // 外呼调节中 可以追溯 电呼 发短信 移交人员调解
            case MeLawCaseConsts::ME_LAW_CASE_WHTJZ_3:
                $canFollow = true;
                $canCallPhone = true;
                $canSendSMS = true;
                $canToTj = true;
                $canOverLawCase = true;
                $canInfoEditPhone = true;
                break;
            // 人员调解中 可以创建会议纪要 新增会议回访 提交协议 转诉讼 转执行 结案
            case MeLawCaseConsts::ME_LAW_CASE_RYTJZ_4:
                $canMediateMeeting = true;
                $canMeetingFallback = true;
                $canCommitAgreement = true;
                // TODO 暂时只允许结案
                $canToSuSong = false;
                $canToZhiXing = false;
                $canOverLawCase = true;
                break;
            // 诉讼中 结案 回访记录 执行 新增诉讼记录【暂时没有这个权限】
            case MeLawCaseConsts::ME_LAW_CASE_SSZ_5:
                $canOverLawCase = true;
                $canMeetingFallback = true;
                // TODO
                $canToSuSong = false;

                break;
            // 执行中
            case MeLawCaseConsts::ME_LAW_CASE_ZXZ_6:
                break;
            // 结案
            case MeLawCaseConsts::ME_LAW_CASE_JA_7:
                break;
            // 结案未回款
            case MeLawCaseConsts::ME_LAW_CASE_JAWHK_8:
                break;
            // 已受理
            case MeLawCaseConsts::ME_LAW_CASE_YSL_9:
                $canToWh = true;
                $canToSelf = true;
                break;
        }

        $data['auth'] = [
            "canDistribution" => $canDistribution,
            "canInfo" => $canInfo,
            "canEdit" => $canEdit,
            "canDelete" => $canDelete,
            "canFollow" => $canFollow,
            "canCallPhone" => $canCallPhone,
            "canSendSMS" => $canSendSMS,
            "canToTj" => $canToTj,
            "canOverLawCase" => $canOverLawCase,
            "canToWh" => $canToWh,
            "canToSelf" => $canToSelf,
            "canInfoEditPhone" => $canInfoEditPhone,
            "canCreateNotice" => $canCreateNotice,
            "canCreateMediation" => $canCreateMediation,
            "canMediateMeeting" => $canMediateMeeting,
            "canMeetingFallback" => $canMeetingFallback,
            "canCommitAgreement" => $canCommitAgreement,
            "canToSuSong" => $canToSuSong,
            "canToZhiXing" => $canToZhiXing,
            "canAcceptance" =>$canAcceptance,
            "canRefundAcceptance" =>$canRefundAcceptance,
        ];
        return $data;
    }

    /**
     * 处理详情和列表的基础数据
     * @param $data
     * @return mixed
     */
    private function disposeDataV2($data,$staffAll){
        $res = array_column(MeLawCaseStatusEnum::getEnumMapList(),'type','value');
        $data['law_case_status_type'] = $res[$data['law_case_status']];
        static $flag = true;
        static $MeLawCasePhoneModel = "";
        static $MeLawCaseStatusEnum = "";
        if($flag){
            $MeLawCasePhoneModel = new MeLawCasePhoneModel();
            $MeLawCaseStatusEnum = new MeLawCaseStatusEnum();
            $flag = false;
        }

        $data['law_case_status_str'] = $MeLawCaseStatusEnum::getEnumMeaningByEnumCode($data['law_case_status']);
        $data['mediator_str']  = isset($data['mediator_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['mediator_id']): "-";
        $data['seats_str']  = isset($data['seats_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['seats_id']): "-";
        // 存在手机号处理 按照，分个字符串以后查询具体手机号详情
        $data['phone_list'] = [];
        if(isset($data['respondent_phone_ids'])){
            $phones = explode(',',$data['respondent_phone_ids']);
            $data['phone_list'] = $MeLawCasePhoneModel->getByIds($phones,[
                'law_case_phone_id',
                'law_case_phone_id as key',
                'phone_number',
                'phone_status',
                'phone_status as phone_status_str',
                'is_law_case_main_phone',
                'created_time',
                'updated_time'
            ]);
        }

        // 逾期天数
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_day'] = (int)((time() - strtotime($data['loans_overdue_time'])) / 86400);
        }
        if(isset($data['loans_periods_number'])){
            // 剩余期数
            $data['loans_periods_remain_number'] = $data['loans_periods_number'] - $data['loans_periods_input_number'];
        }
        if(isset($data['owner_id'])){
            $data['owner_name'] = StaffFunc::getStaffNameByStaffId($staffAll,$data['owner_id']) ?? "-";
        }
        // 时间处理
        if(isset($data['loans_time'])){
            $data['loans_time'] = date('Y-m-d',strtotime($data['loans_time']));
        }
        if(isset($data['loans_start_time'])){
            $data['loans_start_time'] = date('Y-m-d',strtotime($data['loans_start_time']));
        }
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_time'] = date('Y-m-d',strtotime($data['loans_overdue_time']));
        }
        if(isset($data['created_at'])){
            $data['created_at'] = date('Y-m-d',strtotime($data['created_at']));
        }
        if(isset($data['updated_at'])){
            $data['updated_at'] = date('Y-m-d',strtotime($data['updated_at']));
        }

        return $data;
    }

    /**
     * 处理详情和列表的基础数据
     * @param $data
     * @return mixed
     */
    private function disposeData($data,$staffAll){
        $res = array_column(MeLawCaseStatusEnum::getEnumMapList(),'type','value');
        $data['law_case_status_type'] = $res[$data['law_case_status']];
        static $flag = true;
        static $MeClientModel = "";
        static $MeLawCasePhoneModel = "";
        static $MeLawCaseStatusEnum = "";
        if($flag){
            $MeClientModel = new MeClientModel();
            $MeLawCasePhoneModel = new MeLawCasePhoneModel();
            $MeLawCaseStatusEnum = new MeLawCaseStatusEnum();
            $flag = false;
        }

        $data['client_name'] = $MeClientModel->getById($data['client_id'],['client_name'])['client_name'] ?? "-";
        $data['law_case_status_str'] = $MeLawCaseStatusEnum::getEnumMeaningByEnumCode($data['law_case_status']);
        $data['mediator_str']  = isset($data['mediator_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['mediator_id']): "-";
        $data['seats_str']  = isset($data['seats_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['seats_id']): "-";
        // 存在手机号处理 按照，分个字符串以后查询具体手机号详情
        if(isset($data['respondent_phone_ids'])){
            $phones = explode(',',$data['respondent_phone_ids']);
            $data['phone_list'] = $MeLawCasePhoneModel->getByIds($phones,[
                'law_case_phone_id',
                'law_case_phone_id as key',
                'phone_number',
                'phone_status',
                'phone_status as phone_status_str',
                'is_law_case_main_phone',
                'created_time',
                'updated_time'
            ]);
        }

        // 逾期天数
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_day'] = (int)((time() - strtotime($data['loans_overdue_time'])) / 86400);
        }
        if(isset($data['loans_periods_number'])){
            // 剩余期数
            $data['loans_periods_remain_number'] = $data['loans_periods_number'] - $data['loans_periods_input_number'];
        }
        if(isset($data['owner_id'])){
            $data['owner_name'] = StaffFunc::getStaffNameByStaffId($staffAll,$data['owner_id']) ?? "-";
        }
        // 时间处理
        if(isset($data['loans_time'])){
            $data['loans_time'] = date('Y-m-d',strtotime($data['loans_time']));
        }
        if(isset($data['loans_start_time'])){
            $data['loans_start_time'] = date('Y-m-d',strtotime($data['loans_start_time']));
        }
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_time'] = date('Y-m-d',strtotime($data['loans_overdue_time']));
        }
        if(isset($data['created_at'])){
            $data['created_at'] = date('Y-m-d',strtotime($data['created_at']));
        }
        if(isset($data['updated_at'])){
            $data['updated_at'] = date('Y-m-d',strtotime($data['updated_at']));
        }

        return $data;
    }

    /**
     * 数据列表的处理
     * @param $data
     * @param $staffAll
     * @return mixed
     */
    private function disposeListData($data,$staffAll){
        $res = array_column(MeLawCaseStatusEnum::getEnumMapList(),'type','value');
        $data['law_case_status_type'] = $res[$data['law_case_status']];
        static $flag = true;
        static $MeLawCaseStatusEnum = "";
        if($flag){
            $MeLawCaseStatusEnum = new MeLawCaseStatusEnum();
            $flag = false;
        }
        $data['law_case_status_str'] = $MeLawCaseStatusEnum::getEnumMeaningByEnumCode($data['law_case_status']);
        $data['mediator_str']  = isset($data['mediator_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['mediator_id']): "-";
        $data['seats_str']  = isset($data['seats_id']) ? StaffFunc::getStaffNameByStaffId($staffAll,$data['seats_id']): "-";
        // 逾期天数
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_day'] = (int)((time() - strtotime($data['loans_overdue_time'])) / 86400);
        }
        if(isset($data['loans_periods_number'])){
            // 剩余期数
            $data['loans_periods_remain_number'] = $data['loans_periods_number'] - $data['loans_periods_input_number'];
        }
        if(isset($data['owner_id'])){
            $data['owner_name'] = StaffFunc::getStaffNameByStaffId($staffAll,$data['owner_id']) ?? "-";
        }
        // 时间处理
        if(isset($data['loans_time'])){
            $data['loans_time'] = date('Y-m-d',strtotime($data['loans_time']));
        }
        if(isset($data['loans_start_time'])){
            $data['loans_start_time'] = date('Y-m-d',strtotime($data['loans_start_time']));
        }
        if(isset($data['loans_overdue_time'])){
            $data['loans_overdue_time'] = date('Y-m-d',strtotime($data['loans_overdue_time']));
        }
        if(isset($data['created_at'])){
            $data['created_at'] = date('Y-m-d',strtotime($data['created_at']));
        }
        if(isset($data['updated_at'])){
            $data['updated_at'] = date('Y-m-d',strtotime($data['updated_at']));
        }

        return $data;
    }

    /**
     * 处理我的外呼数据
     * @param $data
     * @return mixed
     */
    private function disposeDataWhV2($data,$isInfo = false){
        static $flag = true;
        static $smsLogModel;
        if($flag){
            $smsLogModel = (new SMSLogModel());
            $flag = false;
        }
        if($isInfo){
            $data['sms_list'] = $smsLogModel->getLawCaseList($data['law_case_id']);
        }
        $data['sms_send_number'] = $smsLogModel->getLawCaseCount($data['law_case_id']);
        $data['sms_send_last_time'] = isset($smsLogModel->getLastCreatedTimeByLawCaseId($data['law_case_id'])['created_time']) ? $smsLogModel->getLastCreatedTimeByLawCaseId($data['law_case_id'])['created_time'] : "-";
        // TODO 这里暂时是写死的
        $data['check_code'] = rand(0,9999)."-".rand(0,9999);
        $data['appoint_case_date'] = date("Y-m-d",time());
        return $data;
    }


    /**
     * 处理我的外呼数据
     * @param $data
     * @return mixed
     */
    private function disposeDataWh($data,$isInfo = false){
        static $flag = true;
        static $meLawCaseFollowModel;
        static $smsLogModel;
        if($flag){
            $meLawCaseFollowModel = (new MeLawCaseFollowModel());
            $smsLogModel = (new SMSLogModel());
            $flag = false;
        }
        if($isInfo){
             $data['sms_list'] = $smsLogModel->getLawCaseList($data['law_case_id']);
        }

        $data['sms_send_number'] = $smsLogModel->getLawCaseCount($data['law_case_id']);
        $data['sms_send_last_time'] = isset($smsLogModel->getLastCreatedTimeByLawCaseId($data['law_case_id'])['created_time']) ? $smsLogModel->getLastCreatedTimeByLawCaseId($data['law_case_id'])['created_time'] : "-";

        // TODO 这里暂时是写死的
        $data['check_code'] = rand(0,9999)."-".rand(0,9999);
        $data['appoint_case_date'] = date("Y-m-d",time());
        // 获取当前案件最新的外呼状态
        $res = $meLawCaseFollowModel->getNexExtStatusByLawCaseId($data['law_case_id']);
        $data['law_case_wh_follow_status'] =$res['law_case_wh_follow_status']??0;
        $data['recently_follow'] =$res['created_time']??0;
        return $data;
    }


    public function lawCaseCancelAllocation(){
        $data = request()->all();
        if(!isset($data['law_case_ids'])){
            return ResponseFunc::returnJson(
                'error',
                null,
                '案件不能为空',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $lawCaseModel = new MeLawCase();
        try {
            $res = $lawCaseModel->whereIn('law_case_id',$data['law_case_ids'])->update([
                'seats_id' => 0
            ]);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '取消案件分配成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '取消案件分配失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

    }


    public function lawCaseAllocation(lawCaseAllocationInfoRequest $infoRequest){
        $data = $infoRequest->all();

        $lawCaseModel = new MeLawCase();
        // 数据操作
//        $lawCaseList = $lawCaseModel->select([
//            'law_case_id as lawCaseId',
//            'loans_output_money_principal as money'
//        ])->where('client_id',15) // 案件必须是外呼调解中的
//            ->where('law_case_status',3) // 案件必须是外呼调解中的
//            ->where('seats_id',0) // 案件必须是待分配的
//            ->where('status',1) // 案件必须是正常未删除
//            ->get();

        $lawCaseList = $lawCaseModel->select([
            'law_case_id as lawCaseId',
            'loans_remaining_principal as money'
        ])->whereIn('law_case_id',$data['law_case_ids'])
            ->where('law_case_status',3) // 案件必须是外呼调解中的
            ->where('seats_id',0) // 案件必须是待分配的
            ->where('status',1) // 案件必须是正常未删除
            ->get();
        $lawCaseAllocation = new MeLawCaseAllocation();
        $assignedCases= $lawCaseAllocation->allocationTypeMoneyNumberGetPost($lawCaseList->toArray(),$data['mediator_ids']);

        $disposeAssignedCases = [];
        // 处理数据方便sql一次性修改数据减少循环
        foreach ($assignedCases as $key => $assignedCase) {
            $disposeAssignedCases[$assignedCase][] = $key;
        }

        // 循环处理好的数据为案件添加 电呼人员id 不修改状态
        DB::beginTransaction();
        try {
            foreach($disposeAssignedCases as $key => $disposeAssignedCase){
                $lawCaseModel->whereIn('law_case_id',$disposeAssignedCase)->update([
                    'seats_id' => $key
                ]);
            }
            DB::commit();
            return ResponseFunc::returnJson(
                'ok',
                null,
                '自动案件分配成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            DB::rollBack();
            return ResponseFunc::returnJson(
                'error',
                null,
                '自动案件分配失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

    }

    /**
     * 获取案件分配详情
     * @param lawCaseAllocationInfoRequest $infoRequest
     * @return \Illuminate\Http\JsonResponse
     */
    public function lawCaseAllocationInfo(lawCaseAllocationInfoRequest $infoRequest){
        $data = $infoRequest->all();
        try {
            // 创建临时表
            DB::statement('CREATE TEMPORARY TABLE cy_temp_ids (fa_id INT, INDEX idx_fa_id (fa_id))');

            // 处理零食表中的数据
            $newArray = array_map(function($value) {
                return ['fa_id' => $value];
            }, $data['law_case_ids']);
            // 插入数据到临时表
            DB::table('temp_ids')->insert($newArray);

            $lawCaseModel = new MeLawCase();
            $lawCaseList = $lawCaseModel->select([
                'law_case_id as lawCaseId',
                'loans_remaining_principal as money'
            ])
            ->join('temp_ids as temp','law_case_id','temp.fa_id')
            ->where('law_case_status',3) // 案件必须是外呼调解中的
            ->where('seats_id',0) // 案件必须是待分配的
            ->where('status',1) // 案件必须是正常未删除
            ->get();

            if(!$lawCaseList->toArray()){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '案件已分配过',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
            $lawCaseAllocation = new MeLawCaseAllocation();
            $res = $lawCaseAllocation->lawCaseAllocation($data['type'],cases: $lawCaseList->toArray(),num_workers: $data['mediator_ids']);
            return ResponseFunc::returnJson(
                'ok',
                $res,
                '自动案件分配成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            dd($exception);
            return ResponseFunc::returnJson(
                'error',
                null,
                '自动案件分配失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 受理
     */
    public function acceptance(AcceptancePostRequest $request){
        $data = $request->all();
        $ids = $data['law_case_ids'];
        // 校验当前 mediator_id 是否为当前登录账号 和状态是否为已分配
        $staffId = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $errorDatas = $this->meLawCaseModel->select(['law_case_id'])
            ->where('mediator_id', $staffId)
            ->where('status', 1)
            ->where('law_case_status', MeLawCaseConsts::ME_LAW_CASE_YFP_2)
            ->whereIn('law_case_id',$ids)
            ->get();
        // 对比两个数组的差异
        $diffCount = 0;
        if($errorDatas){
            $diff = array_diff($ids, array_column($errorDatas->toArray(),'law_case_id'));
            $diffCount = count($diff);
        }
        // 修改当前案件状态为已受理
        try {
            $res = $this->meLawCaseModel->whereIn('law_case_id',$ids)->update([
                'law_case_status'=>MeLawCaseConsts::ME_LAW_CASE_YSL_9
            ]);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'total' => count($ids),
                    'okNumber' => count($ids) - $diffCount,
                    'jumpNumber' => $diffCount
                ],
                '受理成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '受理失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    /**
     * 退理
     */
    public function refundAcceptance(AcceptancePostRequest $request){
        $data = $request->all();
        $ids = $data['law_case_ids'];
        // 校验当前 mediator_id 是否为当前登录账号 和状态是否为已分配
        $staffId = TokenFuc::getCurrentStaffInfo()['staff_id'];
        $errorDatas = $this->meLawCaseModel->select(['law_case_id'])
            ->where('mediator_id', $staffId)
            ->where('status', 1)
            ->where('law_case_status', MeLawCaseConsts::ME_LAW_CASE_YFP_2)
            ->whereIn('law_case_id',$ids)
            ->get();
        // 对比两个数组的差异
        $diffCount = 0;
        if($errorDatas){
            $diff = array_diff($ids, array_column($errorDatas->toArray(),'law_case_id'));
            $diffCount = count($diff);
        }
        // 修改当前案件状态为待分配并且删除调解员
        try {
            $res = $this->meLawCaseModel
                ->where('law_case_status', MeLawCaseConsts::ME_LAW_CASE_YFP_2)
                ->whereIn('law_case_id',$ids)
                ->update([
                'law_case_status'=>MeLawCaseConsts::ME_LAW_CASE_DFP_1,
                'mediator_id' => null
            ]);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'total' => count($ids),
                    'okNumber' => count($ids) - $diffCount,
                    'jumpNumber' => $diffCount
                ],
                '取消受理成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '取消受理失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }


}